package com.das.mechanic_base.widget;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseDialog;
import com.das.mechanic_base.base.X3IBaseView;
import com.das.mechanic_base.bean.alone.SpeechBean;
import com.das.mechanic_base.bean.task.FollowCarAllBean;
import com.das.mechanic_base.bean.task.SaveTodoBean;
import com.das.mechanic_base.bean.task.ServiceCreateTask;
import com.das.mechanic_base.bean.even.DeleteFriends;
import com.das.mechanic_base.mapi.api.NetWorkHttp;
import com.das.mechanic_base.mapi.response.HttpCallBack;
import com.das.mechanic_base.mapi.schedulers.RxSchedulersHelper;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.LanguageUtiles;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.das.mechanic_base.utils.X3TimeUtils;
import com.das.mechanic_base.utils.X3ToastUtils;
import com.das.mechanic_base.utils.X3Utils;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class X3TaskInputPopWindow extends X3BaseDialog implements TextWatcher, View.OnClickListener, X3BottomTimeTaskDialog.IOnClickTime, X3BottomTaskUserDialog.IOnSearchUser, DialogInterface.OnDismissListener, X3TaskShortDialog.IOnShowSelect {

    private EditText et_input;
    private TextView tv_num;
    private TextView tv_clear;
    private ImageView tv_add;
    private TextView iv_voice;
    private LinearLayout ll_start;
    private RelativeLayout rl_edit;
    private Button btn_create;
    private X3AloneSoundView as_view;
    private TextView tv_end;
    private LinearLayout rl_input;

    private RelativeLayout rl_word;

    private RelativeLayout rl_remind;
    private RelativeLayout rl_priority;
    private RelativeLayout rl_custom;

    private TextView tv_remind;
    private ImageView iv_remind;

    private ImageView iv_custom;
    private TextView tv_custom;

    private TextView tv_notify;
    private ImageView iv_priority;

    private ImageView iv_custom_clear;
    private ImageView iv_remind_clear;
    private ImageView iv_notify_clear;

    private X3SwipeBackLayout sl_view;

    private RelativeLayout rl_notify;
    private View v_click;
    private TextView tv_medium;
    private TextView tv_high;
    private TextView tv_low;

    /**
     * isShow == true ? 已经创建过直接展示 ： 没有创建过 则创建
     */
    boolean isShow = false;

    /**
     * 点击取消的时候判断是否显示弹窗提示
     */
    boolean isShowDailg = false;

    /**
     * selectShow == true ? 从查看dailog直接过来展示 ： 没有创建过 则创建
     */
    boolean selectShow = false;

    // 待办事项id
    private long id;

    boolean isH5;

    /**
     * 语音听写
     */
    private SpeechRecognizer mIat;
    private X3BottomTimeTaskDialog timeTaskDialog;
    private X3BottomTaskUserDialog userDialog;

    private long carOwnUserId;
    private String notifyStatus = "NONTH";
    private String selectTime;
    private FollowCarAllBean.ListBean userBean;
    private SaveTodoBean todoBean;
    private X3PointDialog cancelDialog;

    private String carOwnerName;
    private X3TaskShortDialog shortDialog;
    private String today;
    private int inputHeight;
    private boolean isSubmit;

    public X3TaskInputPopWindow(@NonNull Context context) {
        super(context,R.style.MatchBottomSheetDialog);
    }

    @Override
    protected void initView() {
        et_input = getView(R.id.et_input);
        tv_num = getView(R.id.tv_num);
        tv_clear = getView(R.id.tv_clear);
        tv_add = getView(R.id.tv_add);
        iv_voice = getView(R.id.iv_voice);
        ll_start = getView(R.id.ll_start);
        rl_edit = getView(R.id.rl_edit);
        btn_create = getView(R.id.btn_create);
        as_view = getView(R.id.as_view);
        tv_end = getView(R.id.tv_end);
        rl_remind = getView(R.id.rl_remind);
        rl_priority = getView(R.id.rl_priority);
        rl_custom = getView(R.id.rl_custom);
        tv_remind = getView(R.id.tv_remind);
        iv_remind = getView(R.id.iv_remind);
        tv_custom = getView(R.id.tv_custom);
        iv_custom = getView(R.id.iv_custom);
        tv_notify = getView(R.id.tv_notify);
        iv_priority = getView(R.id.iv_priority);
        iv_custom_clear = getView(R.id.iv_custom_clear);
        iv_remind_clear = getView(R.id.iv_remind_clear);
        iv_notify_clear = getView(R.id.iv_notify_clear);
        sl_view = getView(R.id.sl_view);
        rl_notify = getView(R.id.rl_notify);
        v_click = getView(R.id.v_click);
        tv_high = getView(R.id.tv_high);
        tv_medium = getView(R.id.tv_medium);
        tv_low = getView(R.id.tv_low);
        rl_word = getView(R.id.rl_word);
        rl_input = getView(R.id.rl_input);

        tv_high.setOnClickListener(this);
        tv_medium.setOnClickListener(this);
        tv_low.setOnClickListener(this);
        v_click.setOnClickListener(this);
        iv_notify_clear.setOnClickListener(this);
        iv_remind_clear.setOnClickListener(this);
        iv_custom_clear.setOnClickListener(this);
        et_input.setOnClickListener(this);
        tv_clear.setOnClickListener(this);
        tv_add.setOnClickListener(this);
        iv_voice.setOnClickListener(this);
        tv_end.setOnClickListener(this);
        rl_remind.setOnClickListener(this);
        rl_priority.setOnClickListener(this);
        rl_custom.setOnClickListener(this);
        btn_create.setOnClickListener(this);

        et_input.addTextChangedListener(this);

        sl_view.setIsBackToEnd(false);
        sl_view.setSwipeBackListener(new X3SwipeBackLayout.OnSwipeBackListener() {
            @Override
            public void onViewPositionChanged(View mView, float swipeBackFraction, float swipeBackFactor) {
                v_click.performClick();
            }

            @Override
            public void onViewSwipeFinished(View mView, boolean isEnd) {
                if (isEnd) {
                    dismiss();
                }
            }

            @Override
            public void onViewBack() {
                // 下拉弹回
                backTaskInput();
            }
        });

        setOnKeyListener((dialog, keyCode, event) -> {
            if(keyCode == KeyEvent.KEYCODE_BACK){
                backTaskInput();
                return true;
            }
            return false;
        });

        et_input.setOnTouchListener((v, event) -> {
            // 当触摸的是EditText & 当前EditText可滚动时，则将事件交给EditText处理；
            if ((v.getId() == R.id.et_input && canVerticalScroll(et_input))) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
                // 否则将事件交由其父类处理
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                }
            }
            return false;
        });
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param //editText需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText contentEt) {
        //滚动的距离
        int scrollY = contentEt.getScrollY();
        //控件内容的总高度
        int scrollRange = contentEt.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = contentEt.getHeight() - contentEt.getCompoundPaddingTop() - contentEt.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }
        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    public void hideRlInputBottom() {
        rl_input.setPadding(rl_input.getPaddingLeft(),rl_input.getPaddingTop(),rl_input.getPaddingRight(),0);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }

    private Handler mHandler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            et_input.setFocusable(true);
            et_input.setFocusableInTouchMode(true);
            et_input.requestFocus();
            InputMethodManager inputManager = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(et_input, 0);
        }
    };

    private ViewTreeObserver.OnGlobalLayoutListener mGlobalLayoutListener = () -> {
        Rect rect = new Rect();
        //获取当前窗口实际的可见区域
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int displayHeight = rect.bottom - rect.top;

        int height = getWindow().getDecorView().getHeight();

        inputHeight = height - displayHeight;

        if (inputHeight != rl_input.getPaddingBottom()) {
            rl_input.setPadding(rl_input.getPaddingLeft(),rl_input.getPaddingTop(),rl_input.getPaddingRight(), inputHeight);
        }
    };

    @Override
    protected float getWindowWidth() {
        return 1;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.x3_create_task_item;
    }

    private void backTaskInput() {
        String input = et_input.getText().toString();
        if (X3StringUtils.isEmpty(input)) {
            dismiss();
        }else {
            if (todoBean != null) {
                if (input.equals(todoBean.content) && notifyStatus.equals(todoBean.priorityLevel) && carOwnUserId == todoBean.carOwnerUserId
                        && (selectTime.equals(todoBean.remindTime) || (X3StringUtils.isEmpty(selectTime) && X3StringUtils.isEmpty(todoBean.remindTime)))) {
                    dismiss();
                    return;
                }
            }
            if (cancelDialog == null) {
                cancelDialog = new X3PointDialog(mContext,mContext.getString(R.string.cancel_task_title),mContext.getString(R.string.cancel_task_des),
                        mContext.getString(R.string.x3_cancel_info),mContext.getString(R.string.x3_affirm_string));
            }
            cancelDialog.show();
            cancelDialog.setiBtnClick(new X3PointDialog.IBtnClick() {
                @Override
                public void iBtnAffirmClick() {
                    if (cancelDialog != null) {
                        cancelDialog.dismiss();
                    }
                    X3TaskInputPopWindow.this.dismiss();
                }

                @Override
                public void iBtnCancelClick() {
                    if (cancelDialog != null) {
                        cancelDialog.dismiss();
                    }
                }
            });
        }
    }

    public void showTaskInput(boolean isShow, boolean isShowDailg, boolean selectShow, boolean isH5, long id, ServiceCreateTask getBean) {
        this.isShow = isShow;
        this.isShowDailg = isShowDailg;
        this.selectShow = selectShow;
        this.isH5 = isH5;
        this.id = id;
        this.todoBean = new SaveTodoBean();
        this.isSubmit = false;

        getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(mGlobalLayoutListener);

        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //字符表示，如星期F
        today = sdf.format(d);

        et_input.setText("");
        // 初始化选中的状态都
        iv_remind_clear.performClick();
        iv_custom_clear.performClick();
        iv_notify_clear.performClick();

        //selectShow是从查看进来的，都不可编辑
        if (selectShow) {
            et_input.setEnabled(false);
            rl_remind.setClickable(false);
            rl_custom.setClickable(false);
            btn_create.setVisibility(View.GONE);
            rl_priority.setClickable(false);
        }

        mHandler.postDelayed(runnable,200);

        //从标记回访进来 优先级默认为high
        if (isShowDailg) {
            iOnClickTaskLevel("LEVEL_HI");
        }

        if (id != 0) {
            getToDo(id);
        }

        if (getBean == null) {
            return;
        }
        String userName = X3StringUtils.isEmpty(getBean.getCarOwnerName()) ? "-" : getBean.getCarOwnerName();

        if (isShowDailg) {
            //默认待办事项为回访+车主名称
            et_input.setText(mContext.getString(R.string.x3_visit) + userName);
        }

        userBean = new FollowCarAllBean.ListBean();
        userBean.setName(userName);
        if (!X3StringUtils.isEmpty(getBean.getCarOwnerUserId())) {
            userBean.setId(Integer.parseInt(getBean.getCarOwnerUserId()));
        }
        iOnSelectUser(userBean);
    }

    /**
     * 获取已经创建好的待办事项详情
     * @param id
     */
    private void getToDo(long id) {
        NetWorkHttp.getApi().getToDo(id)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<SaveTodoBean>() {
                    @Override
                    protected void onDone(SaveTodoBean saveTodoBean) {
                        getToDoSuccess(saveTodoBean);
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {

                    }
                });
    }

    /**
     * 获取待办事项详情
     * @param saveTodoBean
     */
    private void getToDoSuccess(SaveTodoBean saveTodoBean) {
        if (saveTodoBean == null) {
            return;
        }
        this.todoBean = saveTodoBean;

        String content = todoBean.content;
        if (!X3StringUtils.isEmpty(content)) {
            et_input.setText(content);
            et_input.setSelection(et_input.getText().toString().length());
        }

        String remindTime = todoBean.remindTime;
        iOnClickTimeTask(remindTime);

        iOnClickTaskLevel(todoBean.priorityLevel);

        carOwnUserId = todoBean.carOwnerUserId;
        if (carOwnUserId == 0) {
            iv_custom_clear.performClick();
            return;
        }
        String userName = X3StringUtils.isEmpty(todoBean.carOwnerUserName) ? "-" : todoBean.carOwnerUserName;

        FollowCarAllBean.ListBean listBean = new FollowCarAllBean.ListBean();
        listBean.setId(carOwnUserId);
        listBean.setName(userName);
        iOnSelectUser(listBean);
    }

//    @Override
//    public void onDismiss() {
//        if (et_input != null) {
//            et_input.setText("");
//        }
//        if (iOnDissMiss != null) {
//            iOnDissMiss.onDismiss();
//        }
//        super.onDismiss();
//    }


    IOnDissMiss iOnDissMiss;

    public void setiOnDissMiss(IOnDissMiss iOnDissMiss) {
        this.iOnDissMiss = iOnDissMiss;
    }

    @Override
    public void iOnSelectTaskContent(String content) {
        String input = et_input.getText().toString() + "" + content;
        et_input.setText(input);
        if (X3StringUtils.isEmpty(input)) {
            return;
        }
        String s = et_input.getText().toString();
        et_input.setSelection(s.length());
    }

    public interface IOnDissMiss {
        void onDismiss();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        String content = s.toString();

        btn_create.setBackground(X3StringUtils.isEmpty(content) ? ContextCompat.getDrawable(mContext,R.drawable.x3_shape_rad_4_cor_d5d5) :
                ContextCompat.getDrawable(mContext,R.drawable.x3_alone_dialog_affirm));
        btn_create.setEnabled(!X3StringUtils.isEmpty(content));

        tv_clear.setVisibility(X3StringUtils.isEmpty(content) ? View.GONE : View.VISIBLE);
        if (X3StringUtils.isEmpty(content)) {
            tv_num.setText("0/500");
        }else {
            tv_num.setText(content.length() + "/500");
        }
    }

    @Override
    public void onClick(View v) {
        int vId = v.getId();
        if (vId == R.id.tv_clear) {
            et_input.setText("");
        } else if (vId == R.id.tv_add) {// 添加快捷短语
            if (shortDialog == null) {
                shortDialog = new X3TaskShortDialog(mContext);
                shortDialog.setiOnShowSelect(this);
            }
            shortDialog.show();
        } else if (vId == R.id.iv_add) {
        } else if (vId == R.id.iv_voice) {// 语音识别
            XXPermissions.with((Activity) mContext)
                    .permission(Permission.RECORD_AUDIO)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(List<String> permissions, boolean all) {
                            if (all) {
                                startSoundEdit();
                            } else {
                                XXPermissions.startPermissionActivity(mContext, permissions);
                            }
                        }

                        @Override
                        public void onDenied(List<String> permissions, boolean never) {
                            XXPermissions.startPermissionActivity(mContext, permissions);
                        }
                    });
        } else if (vId == R.id.et_input || vId == R.id.tv_end) {
            isShowSound(false);
            if (mIat != null) {
                mIat.stopListening();
                mIat = null;
            }
        } else if (vId == R.id.rl_remind) {
            X3Utils.hideKeyboard(et_input.getWindowToken(), mContext);
            String remind = tv_remind.getText().toString();
            if (timeTaskDialog == null) {
                timeTaskDialog = new X3BottomTimeTaskDialog(mContext);
                timeTaskDialog.setiOnClickTime(this);
            }
            timeTaskDialog.dateIsSelect(!(X3StringUtils.isEmpty(remind) || mContext.getString(R.string.x3_notice_me).equals(remind)));
            timeTaskDialog.show();
            timeTaskDialog.setOnDismissListener(this);
        } else if (vId == R.id.rl_priority) {//                Utils.hideKeyboard(et_input.getWindowToken(),mContext);
            // 延迟一段时间 不然popupwindow位置不正确
//                new Handler().postDelayed((Runnable) () -> {
//                    if (tasklevelWindow == null) {
//                        tasklevelWindow = new TasklevelWindow((Activity) mContext);
//                    }
//                    tasklevelWindow.setPopupGravityMode(GravityMode.RELATIVE_TO_ANCHOR, GravityMode.RELATIVE_TO_ANCHOR);
//                    tasklevelWindow.setPopupGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
//                    tasklevelWindow.setOffsetY(-ScreenUtils.dipToPx(20,mContext));
//                    tasklevelWindow.showPopupWindow(rl_priority);
//                    tasklevelWindow.setiOnItemCameraClick(TaskInputPopWindow.this);
//                },300);

            rl_remind.post(() -> {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) rl_notify.getLayoutParams();
                layoutParams.leftMargin = X3ScreenUtils.dipToPx(34, mContext) + rl_remind.getWidth() + tv_add.getWidth();
                rl_notify.setLayoutParams(layoutParams);
                v_click.setVisibility(View.VISIBLE);
                rl_notify.setVisibility(View.VISIBLE);
            });
        } else if (vId == R.id.rl_custom) {//                Utils.hideKeyboard(et_input.getWindowToken(),mContext);
            String custom = tv_custom.getText().toString();
            if (X3StringUtils.isEmpty(custom) || mContext.getString(R.string.x3_my_user).equals(custom)) {
                // 弹出选择我的客户
                if (userDialog == null) {
                    userDialog = new X3BottomTaskUserDialog(mContext);
                    userDialog.setiOnSearchUser(this);
                }
                userDialog.show();
                userDialog.setOnDismissListener(this);
                return;
            }
            if (carOwnUserId == 0) {
                return;
            }

            Bundle bundle = new Bundle();
            bundle.putBoolean("isDark",true);
            bundle.putString("title","客户详情页");
            bundle.putString("path", X3Constent.HOME_CUSETOM_DETAIL_URL + carOwnUserId);
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

//            // 跳转到车主 用户详情页
//            Intent intent = new Intent(mContext, GroundPushActivity.class);
//            intent.putExtra("isDark", true);
//            intent.putExtra("title", "客户详情页");
//            intent.putExtra("path", Constent.HOME_CUSETOM_DETAIL_URL + carOwnUserId);
//            mContext.startActivity(intent);
        } else if (vId == R.id.iv_remind_clear) {
            this.selectTime = "";
            RelativeLayout.LayoutParams remindLayout = (RelativeLayout.LayoutParams) tv_remind.getLayoutParams();
            remindLayout.rightMargin = X3ScreenUtils.dipToPx(14, mContext);
            tv_remind.setLayoutParams(remindLayout);
            iv_remind.setImageResource(R.mipmap.x3_task_remind_icon);
            iv_remind_clear.setVisibility(View.GONE);
            tv_remind.setTextColor(Color.parseColor("#313340"));
            tv_remind.setText(mContext.getString(R.string.x3_notice_me));
        } else if (vId == R.id.iv_notify_clear) {
            this.notifyStatus = "NONTH";
            rl_notify.setVisibility(View.GONE);
            v_click.setVisibility(View.GONE);
            iv_priority.setImageResource(R.mipmap.x3_task_priority);
            tv_notify.setTextColor(Color.parseColor("#313340"));
            iv_notify_clear.setVisibility(View.GONE);
            tv_notify.setText(mContext.getString(R.string.x3_priority));
            RelativeLayout.LayoutParams notifyLayout = (RelativeLayout.LayoutParams) tv_notify.getLayoutParams();
            notifyLayout.rightMargin = X3ScreenUtils.dipToPx(14, mContext);
            tv_notify.setLayoutParams(notifyLayout);
        } else if (vId == R.id.iv_custom_clear) {
            this.carOwnUserId = 0;
            this.carOwnerName = "";

            iv_custom.setImageResource(R.mipmap.x3_task_custom);
            tv_custom.setTextColor(Color.parseColor("#313340"));
            iv_custom_clear.setVisibility(View.GONE);
            tv_custom.setText(mContext.getString(R.string.x3_my_user));
            RelativeLayout.LayoutParams customLayout = (RelativeLayout.LayoutParams) tv_custom.getLayoutParams();
            customLayout.rightMargin = X3ScreenUtils.dipToPx(14, mContext);
            tv_custom.setLayoutParams(customLayout);
        } else if (vId == R.id.btn_create) {
            if (isSubmit) {
                return;
            }
            // 创建或者修改待办事项
            if (!X3Utils.isFastClick()) {
                return;
            }
            if (todoBean == null) {
                todoBean = new SaveTodoBean();
            }

            String input = et_input.getText().toString();
            if (X3StringUtils.isEmpty(input)) {
                X3ToastUtils.showMessage(mContext.getString(R.string.x3_task_no_content));
                return;
            }
            todoBean.content = input;
            todoBean.remindTime = selectTime;
            todoBean.carOwnerUserId = carOwnUserId;
            todoBean.carOwnerUserName = carOwnerName;
            todoBean.priorityLevel = notifyStatus;

            isSubmit = true;
            if (isShow) {
                updateToDo(todoBean);
            } else {
                saveToDo(todoBean);
            }
        } else if (vId == R.id.v_click) {
            v_click.setVisibility(View.GONE);
            rl_notify.setVisibility(View.GONE);
            rl_word.setVisibility(View.GONE);
        } else if (vId == R.id.tv_high) {
            v_click.performClick();
            iOnClickTaskLevel("LEVEL_HI");
        } else if (vId == R.id.tv_medium) {
            v_click.performClick();
            iOnClickTaskLevel("LEVEL_MI");
        } else if (vId == R.id.tv_low) {
            v_click.performClick();
            iOnClickTaskLevel("NONTH");
        }
    }

    private void saveToDo(SaveTodoBean todoBean) {
        NetWorkHttp.getApi().saveToDo(todoBean)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        saveToDoSuccess();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        isSubmit = false;
                    }

                    @Override
                    protected void NoNetCallBack() {
                        super.NoNetCallBack();
                        isSubmit = false;
                    }
                });
    }

    /**
     * 更新待办事项
     * @param todoBean
     */
    private void updateToDo(SaveTodoBean todoBean) {
        NetWorkHttp.getApi().updateToDo(todoBean)
                .compose(RxSchedulersHelper.defaultComposeRequest())
                .compose(((X3IBaseView)mContext).bindToLife())
                .subscribe(new HttpCallBack<Object>() {
                    @Override
                    protected void onDone(Object o) {
                        saveToDoSuccess();
                    }

                    @Override
                    protected String LoadingMessage() {
                        return null;
                    }

                    @Override
                    protected void showError(String error) {
                        isSubmit = false;
                    }

                    @Override
                    protected void NoNetCallBack() {
                        super.NoNetCallBack();
                        isSubmit = false;
                    }
                });
    }

    /**
     * 保存和修改待办事项成功
     */
    private void saveToDoSuccess() {
        isSubmit = false;
        DeleteFriends deleteFriends = new DeleteFriends("CREATE_TASK_START");
        EventBus.getDefault().post(deleteFriends);
        X3ToastUtils.showMessage(mContext.getString(R.string.x3_set_notice_success));
        if (iOnRefreshTaskInput != null) {
            iOnRefreshTaskInput.iOnRefreshInput();
        }
        dismiss();
    }

    /**
     * 开启语音识别
     */
    private void startSoundEdit() {
        mIat = SpeechRecognizer.createRecognizer(mContext, i -> Log.e("SSSS", "初始化：" + i));

        //设置语法ID和 SUBJECT 为空，以免因之前有语法调用而设置了此参数；或直接清空所有参数，具体可参考 DEMO 的示例。
        mIat.setParameter(SpeechConstant.CLOUD_GRAMMAR, null);
        mIat.setParameter(SpeechConstant.SUBJECT, null);
        //设置返回结果格式，目前支持json,xml以及plain 三种格式，其中plain为纯听写文本内容
        mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");

        //此处engineType为“cloud”
        mIat.setParameter(SpeechConstant.ENGINE_TYPE, "cloud");
        //设置语音输入语言，zh_cn为简体中文
        if (LanguageUtiles.isZhRCN()) {
            mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        }else {
            mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
        }
        //设置结果返回语言
        mIat.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置语音前端点:静音超时时间，单位ms，即用户多长时间不说话则当做超时处理
        //取值范围{1000～10000}
        mIat.setParameter(SpeechConstant.VAD_BOS, "10000");
        //设置语音后端点:后端点静音检测时间，单位ms，即用户停止说话多长时间内即认为不再输入，
        //自动停止录音，范围{0~10000}
        mIat.setParameter(SpeechConstant.VAD_EOS, "10000");
        //设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        mIat.setParameter(SpeechConstant.ASR_PTT, "1");

        mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");

        //开始识别，并设置监听器
        mIat.startListening(new RecognizerListener() {
            @Override
            public void onVolumeChanged(int i, byte[] bytes) {

            }

            @Override
            public void onBeginOfSpeech() {
                isShowSound(true);
            }

            @Override
            public void onEndOfSpeech() {
                isShowSound(false);
            }

            @Override
            public void onResult(RecognizerResult recognizerResult, boolean b) {
                if (!isShowing()) {
                    return;
                }
                SpeechBean speechBean = new Gson().fromJson(recognizerResult.getResultString(), SpeechBean.class);
                List<SpeechBean.WsBean> ws = speechBean.getWs();
                String strContent = "";
                for (SpeechBean.WsBean wsBean : ws) {
                    strContent = strContent + wsBean.getCw().get(0).getW();
                }
                String content = et_input.getText().toString() + strContent;
                et_input.setText(content);
                if (!X3StringUtils.isEmpty(content)) {
                    if (content.length() < 500) {
                        et_input.setSelection(content.length());
                    }
                }

            }

            @Override
            public void onError(SpeechError speechError) {

            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {

            }
        });
    }

    private void isShowSound(boolean showSound) {
        ll_start.setVisibility(showSound ? View.VISIBLE : View.GONE);
        rl_edit.setVisibility(showSound ? View.GONE : View.VISIBLE);

        if (showSound) {
            X3Utils.hideKeyboard(et_input.getWindowToken(),mContext);
            as_view.startAnim();
        } else {
            X3Utils.showInput(et_input,mContext);
            as_view.stopAnim();
        }
    }

    @Override
    public void dismiss() {
        if (ll_start != null) {
            ll_start.setVisibility(View.GONE);
        }
        if (rl_edit != null) {
            rl_edit.setVisibility(View.VISIBLE);
        }
        if (as_view != null) {
            as_view.stopAnim();
        }
        if (mIat != null) {
            mIat.stopListening();
            mIat = null;
        }
        getWindow().getDecorView().getViewTreeObserver().removeOnGlobalLayoutListener(mGlobalLayoutListener);
        if (mHandler != null) {
            mHandler.removeCallbacks(runnable);
        }
        super.dismiss();

    }

    IOnRefreshTaskInput iOnRefreshTaskInput;

    public void setiOnRefreshTaskInput(IOnRefreshTaskInput iOnRefreshTaskInput) {
        this.iOnRefreshTaskInput = iOnRefreshTaskInput;
    }

    public interface IOnRefreshTaskInput {
        void iOnRefreshInput();
    }

    @Override
    public void iOnClickTimeTask(String selectTimes) {
        this.selectTime = selectTimes;
        if (!X3StringUtils.isEmpty(selectTime)) {
            iv_remind_clear.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tv_remind.getLayoutParams();
            layoutParams.rightMargin = 0;
            tv_remind.setLayoutParams(layoutParams);

            tv_remind.setText(X3DateUtils.HomeLongDateWithTime(selectTime,mContext));
            tv_remind.setTextColor(Color.parseColor("#0077ff"));

            boolean timeCompareSize = X3TimeUtils.getNewTimeCompareSize(today, selectTime);
            if (!timeCompareSize) {
                tv_remind.setTextColor(Color.parseColor("#F64458"));
                iv_remind.setImageResource(R.mipmap.x3_task_complete_time);
            }else {
                tv_remind.setTextColor(Color.parseColor("#0077ff"));
                iv_remind.setImageResource(R.mipmap.x3_task_remind_select_icon);
            }
        } else {
            //显示无提醒
            iv_remind_clear.performClick();
        }
    }

    @Override
    public void iOnSelectUser(FollowCarAllBean.ListBean userBean) {
        this.userBean = userBean;

        carOwnerName = (X3StringUtils.isEmpty(userBean.getName()) ? "-" : userBean.getName());
        carOwnUserId = userBean.getId();

        tv_custom.setText(carOwnerName);
        tv_custom.setTextColor(Color.parseColor("#0077ff"));
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tv_custom.getLayoutParams();
        layoutParams.rightMargin = 0;
        tv_custom.setLayoutParams(layoutParams);
        iv_custom_clear.setVisibility(View.VISIBLE);
        iv_custom.setImageResource(R.mipmap.x3_task_select_custom);

    }

    public void iOnClickTaskLevel(String status) {
        // 选择优先级
        this.notifyStatus = status;
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) tv_notify.getLayoutParams();
        layoutParams.rightMargin = 0;
        tv_notify.setLayoutParams(layoutParams);
        iv_notify_clear.setVisibility(View.VISIBLE);
        switch (status) {
            case "NONTH":
                iv_priority.setImageResource(R.mipmap.x3_task_priority);
                tv_notify.setTextColor(Color.parseColor("#313340"));
                tv_notify.setText(mContext.getString(R.string.x3_task_no));
                break;
            case "LEVEL_MI":
                iv_priority.setImageResource(R.mipmap.x3_task_priority_mi);
                tv_notify.setTextColor(Color.parseColor("#FFC602"));
                tv_notify.setText(mContext.getString(R.string.x3_urgency));
                break;
            case "LEVEL_HI":
                iv_priority.setImageResource(R.mipmap.x3_task_priority_hi);
                tv_notify.setTextColor(Color.parseColor("#F64444"));
                tv_notify.setText(mContext.getString(R.string.x3_more_urgency));
                break;
        }
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        et_input.postDelayed(() -> X3Utils.showInput(et_input,mContext),200);
    }
    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("创建待办事项弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("创建待办事项弹窗");
    }
}
